import React, { PureComponent } from 'react';
import { Form, Input, Button, Row, Col, message } from 'antd';
import IconS from "../../components/IconS";
import {
  systemPlatNewsSendVerificationCode,
  systemPlatNewsVerificationCode,
  systemPerAccountInfoUpdatePassword,
  // systemPerBaseInfoCheckAdmin,
  systemPerBaseInfoCheckPer

} from "../../services/api";
import "./ForgetPassword.less";

const FormItem = Form.Item;
@Form.create()
export default class ForgetPassword extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      count: 60,//短信发送时间限制
      ifSendCode: false,//是否已经发送验证码
    };
  }

  //发送按钮改变
  renderValidButton = () => {
    const { ifSendCode, count } = this.state;
    return (
      <Button type="primary"
        disabled={ifSendCode}
        className="getCaptcha"
        onClick={this.sendCode}
        style={{ marginLeft: 6,marginTop:4 }}
      >
        {ifSendCode ? `${count} s` : '获取验证码'}
      </Button>
    );
  };

  //发送验证
  sendCode = () => {
    // const { ifSendCode } = this.state;
    //获取手机号是否正确
    const mobile = this.props.form.getFieldValue('mobile');
    const mobileErro = this.props.form.getFieldError('mobile');
    console.log('123',mobile);
    if(mobile === '' || mobile === undefined){
      message.error('请填写企业管理员手机号码!');
      return;
    }
    if (mobile !== undefined && mobileErro === undefined) {
      this.setState({ ifSendCode: true });
      this.getNewsCode();
      this.codeTime = window.setInterval(() => {
        const { count } = this.state;
        if (count !== 1) {
          this.setState(preState => ({
            count: preState.count - 1,
          }));
        } else {
          clearInterval(this.codeTime);
          this.setState({ ifSendCode: false, count: 60 });
        }
      }, 1000);
    }
  };

  //获取验证码
  getNewsCode = () => {
    const mobile = this.props.form.getFieldValue("mobile");
    systemPlatNewsSendVerificationCode({ t: "", sign: "", mobile })
      .then((data) => {
        console.log(data);
      }, (err) => {
        console.log(err);
      });
  };
  //检验手机号是否存在
  checkMobile = () => {
    const mobilePhone = this.props.form.getFieldValue("mobile");
    systemPerBaseInfoCheckPer({ mobilePhone }).then((data) => {
      if(data){
        console.log('chaekMobile>>>>>>>>>>>>', data);
        this.setState({
          checkPhone:true
        })
      }
      }, (err) => {
        console.log(err);
        this.setState({
          checkPhone:false
        })
      });
  };

  // // 检验是否管理员
  // checkAdmin = () => {
  //   const mobilePhone = this.props.form.getFieldValue("mobile");
  //   console.log(mobilePhone);
  //   systemPerBaseInfoCheckAdmin({ mobilePhone })
  //     .then((data) => {
  //       console.log('checkAdmin>>>>>>>>>>>>', data);
  //     }, (err) => {
  //       console.log(err.retType);
  //       return false;
  //     });
  // }

  //判断验证码是否正确
  checkCode = () => {
    const code = this.props.form.getFieldValue("code");
    const mobile = this.props.form.getFieldValue("mobile");
    systemPlatNewsVerificationCode({ mobile, code })
      .then((data) => {
        console.log(data);
        this.setState({
          checkCode:true
        })
      }, (err) => {
        console.log('111',err);
        this.setState({
          checkCode:false
        })
      });
  };

  //验证手机号码
  checkPhone = (rule, value, callback) => {
    if (value && !(/^1[0-9]{10}$/).test(value)) {
      callback('请输入正确的手机号码！');
    } else {
      callback();
    }
  };

  //判断密码是否一致
  checkPassword = (rule, value, callback) => {
    //password 第一次密码
    const password = this.props.form.getFieldValue("password");
    //repassword 第2次密码
    const repassword = this.props.form.getFieldValue("repassword");
    if (password !== repassword) {
      callback('两次密码输入不一致');
    } else {
      callback();
    }
  };

  // 表单提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, { mobile, password }) => {
      if (!err) {
        // this.checkAdmin();

        this.checkMobile();
        this.checkCode();
        if(this.state.checkCode && this.state.checkPhone){
          systemPerAccountInfoUpdatePassword({ mobile, password })
            .then((data) => {
                console.log(data);
                message.success(data.msg);
                this.props.history.push("LogOn");
              },
              (err) => {
                console.log(err);
              }
            );
        }
      }
    }, err => {
      console.log(err);
    });
  };



  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 17,
          offset: 7,
        },
      },
    };
    return (
      <div className="password-wrap" >
        <div className="password-header">
          <div className="head-portrait">
            <IconS type="logo-" />
            <span className="head-portrait-text">
              <span style={{ fontSize: "18px" }}>百保盾</span>
              <br />
              <span style={{ fontSize: "12px" }}>改变工作 改变你</span>
            </span>
          </div>
          {/*<div className="head-portrait-register">*/}
            {/*<span*/}
              {/*style={{ cursor: "pointer" }}*/}
              {/*onClick={() => this.props.history.push("Enroll")}*/}
            {/*>*/}
              {/*注册*/}
            {/*</span>*/}
          {/*</div>*/}
        </div>
        <div className="password-content">
          <h1 className="password-title">忘记密码</h1>
          {/*<p className="password-text">当前企业: <span>百川信（厦门）网络信息服务有限公司</span></p>*/}
          <Form onSubmit={this.handleSubmit} >
            <FormItem
              {...formItemLayout}
              label="企业管理员手机号码:"
            >
              {getFieldDecorator('mobile', {
                rules: [{
                  required: true, message: '请输入手机号码!',
                }, {
                validator: this.checkPhone
              }],
              })(
                <Input placeholder="请输入" style={{ width: 400 }} />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="验证码">
              <div style={{ display: 'flex' }}>
                <div style={{ width: 290 }}>
                  {getFieldDecorator('code', {
                    rules: [{
                      required: true, message: '请输入验证码！',
                    }],
                  })(
                    <Input placeholder="请输入" />
                  )}
                </div>
                {this.renderValidButton()}
              </div>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label=" 新密码:"
            >
              {getFieldDecorator('password', {
                rules: [{
                  required: true, message: '请输入您的新密码!',
                }],
              })(
                <Input placeholder="请输入" style={{ width: 400 }}  />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label=" 确认密码:"
            >
              {getFieldDecorator('repassword', {
                rules: [{
                  initialValue:'',
                  required: true, message: '请输入您的确认密码!'
                },
                { validator: this.checkPassword, }
                ],
              })(
                <Input type="password" placeholder="请输入" style={{ width: 400 }} />
              )}
            </FormItem>
            <p style={{ cursor: "pointer" }}
              className="password-goLogin"
              onClick={() => this.props.history.push("LogOn")}
            >
              去登录
            </p>
            <FormItem {...tailFormItemLayout}>
              <Button style={{ marginRight: 16 }} onClick={()=>{
                this.props.history.push("LogOn");
              }}>取消</Button>
              <Button type="primary" htmlType="submit">确定</Button>
            </FormItem>
          </Form>
        </div>
      </div>
    );
  }
}

